package com.winchain.chainbill.bill.biz.send.service.impl;

import com.shell.bee.base.utils.DateUtil;
import com.shell.bee.base.utils.StringUtil;
import com.shell.bee.base.utils.SystemUtil;
import com.shell.bee.state.StateEngine;
import com.shell.bee.state.StateException;
import com.shell.bee.state.engine.State;
import com.shell.bee.state.engine.service.StateMachineService;
import com.shell.framework.utils.CommonDataUtil;
import com.winchain.chainbill.bill.base.po.CbOpt;
import com.winchain.chainbill.bill.base.po.CbRec;
import com.winchain.chainbill.bill.base.service.CbOptService;
import com.winchain.chainbill.bill.biz.send.service.BillOptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("billOptService")
public class BillOptServiceImpl implements BillOptService {
	@Autowired
	private CbOptService cbOptService;
	private static final String BILL_STATE_FLOW_ID = "billStateFlow";

	public void operate(CbRec bill, CbOpt opt) {
		String curState = bill.getBillState();
		String nextState = "";
		String eventCode = opt.getOptCode();
		if (StringUtil.emptyAndNull(eventCode)) {
			opt.setCurState("0");
			opt.setOptCode("");
			opt.setNxtState("S000");
		} else if (("S000".equals(curState))
				&& (("E011".equals(eventCode)) || ("E012".equals(eventCode)) || ("E502".equals(eventCode)))) {
			opt.setCurState("S000");
			nextState = "S005";
			opt.setNxtState(nextState);
		} else {
			try {
				State state = StateEngine.getStateMachineEngine().fire("billStateFlow", curState, eventCode);
				nextState = state.getCode();
			} catch (StateException e) {
				throw new RuntimeException("����������������������", e);
			}
		}
		int optSeq = bill.getOptSeq().intValue();
		bill.setOptSeq(Integer.valueOf(++optSeq));

		opt.setOptId(SystemUtil.getUUID());
		opt.setBillId(bill.getBillId());
		opt.setCurState(curState);
		opt.setNxtState(nextState);
		opt.setOptSeq(Integer.valueOf(optSeq));
		opt.setOprId(CommonDataUtil.getUserId());
		opt.setOptTime(DateUtil.getSystemDateTime());
		this.cbOptService.save(opt);
	}
}
